let loginInfo = require('../../../login.js');
const { getUserInfo } = require('../../../../common/utils/ws/wsxcx-opendata-sdk');
const app = getApp();
const modules = 'cm_universal_form';

Page({
  data: {
    content: '',
    support: 0,
    multiIndex: [0, 0],
    hasimg: false,
    needAuth: false,
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    showModal: false,
    floatItems: [{
      type: 0, // 自定义事件1
      show: true,
      iconClass: 'icon icon-sy',
      event: 'goHome',
    }, {
      type: 0, // 自定义事件1
      show: true,
      iconClass: 'icon icon-rl',
      event: 'toFormLists',
    },
    //  {
    //   type: 4, // 自定义事件1
    //   show: true,
    //   icon: '',
    // }
    ],
    isShowSubmit: false
  },
  onLoad: function (options) {
    options.id && (this.id = options.id);
    let that = this;
    this.getUserInfo();
    app.util.request({
      module: modules,
      url: 'entry/wxapp/api',
      data: {
        type: 2,
        id: that.id || 0,
      },
      success: function (res) {
        if (!res.data.data) {
          return wx.showModal({
            title: '提示',
            content: '暂无表单信息',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateBack();
              }
            },
          });
        }
        let data = res.data.data.fields;
        for (let i = 0; i < data.length; i++) {
          if (data[i].setting == 'checkbox') {
            for (let j = 0; j < data[i].checkbox.length; j++) {
              if (data[i].default.indexOf(data[i].checkbox[j]) >= 0) {
                data[i].checkbox[j] = {
                  fav: data[i].checkbox[j],
                  check: true,
                };
              } else {
                data[i].checkbox[j] = {
                  fav: data[i].checkbox[j],
                  check: false,
                };
              }
            }
          }
        }

        that.setData({
          data: res.data.data,
          forms: data,
          id: res.data.data.id,
          intro: res.data.data.intro,
          title: res.data.data.title,
          button: res.data.data.button,
          content: res.data.data.content,
          msg: res.data.data.msg,
          support: res.data.data.support
        }, () => {
          that.getHistory();
        });
      },
    });
    this.getShareInfo();
  },

  getUserInfo() {
    getUserInfo()
      .then(() => {
      })
      .catch(res => {
        this.setData({
          needAuth: true,
        });
      });
  },

  getHistory() {
    let _this = this;
    if (_this.data.support === 0){
    app.util.request({
      module: modules,
      url: 'entry/wxapp/api',
      data: {
        type: 4,
        form_id: _this.data.id,
      },
      success: function (res) {
        console.log(res);
        let forms = _this.data.forms;
        let dataArr = [];
        if (res.data.data.data) {
          dataArr = res.data.data.data.split(',');
          for (let i = 0; i < forms.length; i++) {
            if (forms[i].setting == 'checkbox') {
              let regexp = dataArr[i].replace(/\./g, ',');
              for (let j = 0; j < forms[i].checkbox.length; j++) {
                if (regexp.indexOf(forms[i].checkbox[j]['fav']) != '-1') {
                  forms[i].checkbox[j] = {
                    fav: forms[i].checkbox[j]['fav'],
                    check: true,
                  };
                } else {
                  forms[i].checkbox[j] = {
                    fav: forms[i].checkbox[j]['fav'],
                    check: false,
                  };
                }
              }
            }
            if (forms[i].setting == 'images') {
              _this.setData({
                hasimg: true,
              });
              if (dataArr[i].indexOf('|') > -1) {
                forms[i].default = dataArr[i].split('|');
                forms[i].isobject = 1;
                forms[i].default.forEach(function (item, itindex, self) {
                  self[itindex] = decodeURIComponent(item || '');
                });
              } else {
                forms[i].default = decodeURIComponent(dataArr[i] || '');
              }
            }
            if (forms[i].setting != 'images') {
              forms[i].default = decodeURIComponent(dataArr[i] || forms[i].default);
            }
          }
          _this.setData({
            forms: forms,
          });
        }
      },
    });
    }
  },
  formSubmit: function (e) {
    let _this = this;
    // let userInfo = wx.getStorageSync('userInfo');
    let id = this.data.id;
    let forms = this.data.forms;
    let submitInfo = e.detail.value;
    console.log(submitInfo);
    let mustArr = [];
    for (var i = 0; i < forms.length; i++) {
      if (forms[i].must - 0) {
        mustArr.push(i);
      }
    }
    console.log(mustArr);

    for (var i = 0; i < mustArr.length; i++) {
      let mustone = forms[mustArr[i]];
      let val = submitInfo[mustArr[i]];
      if (mustone.setting == 'string') {
        if (mustone.rule && mustone.rule != '') {
          mustone.rule = mustone.rule.replace(/\//g, '');
          let reg = new RegExp(mustone.rule);
          if (!reg.test(val)) {
            return wx.showModal({
              title: '提示',
              content: mustone.msg ? mustone.msg : `${mustone.title}格式有误`,
              showCancel: false,
            });
          }
        } else {
          if (val == '') {
            wx.showModal({
              title: '提示',
              content: `${mustone.title}不能为空`,
              showCancel: false,
            });
            return;
          }
        }
      }
      if (mustone.setting == 'images') {
        if (mustone.isobject == 1 && (mustone.default.length == 0 || mustone.default.length > 9)) {
          wx.showModal({
            title: '提示',
            content: `${mustone.title}限制为1-9张图片`,
            showCancel: false,
          });
          return;
        } else if (mustone.isobject != 1 && !mustone.default) {
          wx.showModal({
            title: '提示',
            content: `${mustone.title}不能为空`,
            showCancel: false,
          });
          return;
        }
      } else {
        if (val == '') {
          wx.showModal({
            title: '提示',
            content: `${mustone.title}不能为空`,
            showCancel: false,
          });
          return;
        }
      }
    }

    let str = '';
    for (var i = 0; i < forms.length; i++) {
      let a = '';
      if (typeof forms[i].default === 'object' && forms[i].setting != 'images') {
        forms[i].default = forms[i].default.join('.');
      }
      if (forms[i].setting == 'images') {
        if (forms[i].isobject == 1) {
          forms[i].default.forEach(function (item, itindex, self) {
            self[itindex] = encodeURIComponent(item);
          });
          a = forms[i].default.join('|');
        }
      } else {
        a = encodeURIComponent(forms[i].default);
      }
      str += a + ',';
    }
    str = str.substring(0, str.length - 1);
    let a = str.replace(/,/g, '');
    if (a !== '') {
      app.util.request({
        module: modules,
        url: 'entry/wxapp/api',
        data: {
          type: 3,
          data: str,
          form_id: id,
        },
        method: 'POST',
        success: function (res) {
          _this.sendFromInfo();
          _this.setData({
            isShowSubmit: true
          })
        },
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '提交内容不能为空',
        showCancel: false,
      });
    }
  },

  contact(){
    this.setData({
      showModal: false,
    })
  },
  cancel(){
    this.setData({
      isShowSubmit: false,
    })
    const pages = getCurrentPages();
    if (pages && pages.length > 1) {
      wx.navigateBack();
    } else {
      this.goHome();
    }
  },
  input: function (e) {
    let that = this;
    let forms = that.data.forms;
    let index = e.currentTarget.dataset.index;
    let value = e.detail.value;
    forms[index].default = value;
    that.setData({
      forms: forms,
    });
  },
  radio: function (e) {
    let that = this;
    let forms = that.data.forms;
    let index = e.currentTarget.dataset.index;
    let value = e.detail.value;
    forms[index].default = value;
    that.setData({
      forms: forms,
    });
  },
  checkbox: function (e) {
    let that = this;
    let forms = that.data.forms;
    let index = e.currentTarget.dataset.index;
    let value = e.detail.value;
    forms[index].default = value;
    let checkbox = forms[index].checkbox;
    for (let i = 0; i < checkbox.length; i++) {
      if (value.join('').indexOf(checkbox[i].fav) >= 0) {
        checkbox[i].check = true;
      } else {
        checkbox[i].check = false;
      }
    }
    that.setData({
      forms: forms,
    });
  },
  selector(e) {
    let that = this;
    let forms = that.data.forms;
    let index = e.currentTarget.dataset.index;
    let multiIndex = e.detail.value;
    forms[index].default = forms[index].radio[0][multiIndex[0]] + ' / ' + forms[index].radio[1][multiIndex[1]];
    that.setData({
      forms,
      multiIndex,
    });
  },
  selectSingel: function (e) {
    let that = this;
    let forms = that.data.forms;
    let index = e.currentTarget.dataset.index;
    let value = e.detail.value;
    forms[index].default = forms[index].radio[value];
    that.setData({
      forms: forms,
    });
  },
  time: function (e) {
    let that = this;
    let forms = that.data.forms;
    let index = e.currentTarget.dataset.index;
    let value = e.detail.value;
    forms[index].default = value;
    that.setData({
      forms: forms,
    });
  },
  date: function (e) {
    let that = this;
    let forms = that.data.forms;
    let index = e.currentTarget.dataset.index;
    let value = e.detail.value;
    forms[index].default = value;
    that.setData({
      forms: forms,
    });
  },
  chooseImage: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let forms = that.data.forms;
    loginInfo.upload({
      count: 9,
      success: function (res) {
        if (forms[index].isobject != 1) {
          let origindata = forms[index].default;
          forms[index].default = [];
          if (origindata) {
            forms[index].default[0] = origindata;
          }
          forms[index].isobject = 1;
          that.setData({ forms });
        }
        forms[index].default.push(res.url);
        if (forms[index].isobject == 1 && forms[index].default.length > 9) {
          forms[index].default.length = 9;
          that.setData({ forms });
          wx.showModal({
            title: '提示',
            content: '最多上传9张图片',
            showCancel: false,
          });
          return;
        }
        that.setData({
          forms: forms,
        });
      },
    });
  },
  delimg(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let imgindex = e.currentTarget.dataset.imgindex;
    let forms = that.data.forms;
    if (forms[index].isobject == 1) {
      forms[index].default.splice(imgindex, 1);
    } else {
      forms[index].default = [];
      forms[index].isobject = 1;
    }
    this.setData({
      forms,
    });
  },

  toFormLists() {
    const pages = getCurrentPages();
    if (pages.length > 2) {
      const prevPage = pages[pages.length - 2];
      if (prevPage.route === 'cm_universal_form/pages/form/formlist/formlist') {
        wx.navigateBack({
          delta: 1,
        });
        return;
      }
    }
    app.util.navigateTo('cm_universal_form/pages/form/formlist/formlist');
  },

  getShareInfo() {
    app.util.request({
      url: 'entry/wxapp/api',
      module: 'cm_universal_form',
      data: {
        type: 5,
      },
      method: 'GET',
      success: res => {
        console.log('=====getShareInfo success', res);
        res.data && res.data.data && this.setData({
          shareInfo: res.data.data,
        });

        wx.setNavigationBarTitle({
          title: res.data && res.data.data && res.data.data.alias || '详情',
        });
      },
    });
  },

  onShareAppMessage() {
    const { shareInfo: { img_url: imageUrl = '', title = '' }} = this.data;
    return {
      title,
      imageUrl,
    };
  },

  sendFromInfo() {
    const { id = '' } = this.options;
    app.util.request({
      url: 'entry/wxapp/api',
      module: 'cm_universal_form',
      data: {
        type: 7,
        id,
      },
      method: 'GET',
      success: res => {
        console.log('=====sendFromInfo success', res);
      },
    });
  },

  goHome() {
    const isCompanyCloudTemplate = Number(app.siteInfo.isCloudTemplate) === 1;
    if (isCompanyCloudTemplate) {  // 企业云端发布
      app.util.navigateTo('ws_micro_company_collection/pages/index/index', '', true);
      return;
    }
    let appJson = app.siteInfo.appJson[app.tabbarindex || 0];
    const url = appJson.homePage || (appJson.tabBar && appJson.tabBar.list && appJson.tabBar.list[0].pagePath);
    app.util.navigateTo(url, {}, 'all');
  },
});
